import os

# 定义消费类别映射字典
CATEGORY_MAP = {
    "餐饮": "food",
    "文具": "stat",
    "交通": "trans",
    "娱乐": "fun",
    "其他": "other",
    "food": "餐饮",
    "stat": "文具",
    "trans": "交通",
    "fun": "娱乐",
    "other": "其他"
}

# 定义文件路径
RECORD_FILE = "我的校园消费记录.txt"

def load_records(path):
    """读取并返回历史账本"""
    if not os.path.exists(path):  # 文件不存在时创建空字典
        return {}
    try:
        with open(path, "r", encoding="utf-8") as file:
            records = eval(file.read())  # 将字符串还原为字典
            if not isinstance(records, dict):
                raise ValueError("文件内容格式错误，应为字典")
            return records
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return {}

def save_records(path, data):
    """写回最新账本"""
    try:
        with open(path, "w", encoding="utf-8") as file:
            file.write(str(data))  # 将字典转为字符串写入文件
    except Exception as e:
        print(f"保存文件时发生错误：{e}")

def input_records():
    """循环收集本次用户输入"""
    records = {}
    print("请输入消费记录（输入 q 结束）：")
    while True:
        category_input = input("消费类别（餐饮/food 文具/stat 交通/trans 娱乐/fun 其他/other）：").strip()
        if category_input.lower() == 'q':
            break
        category = CATEGORY_MAP.get(category_input)
        if not category:
            print("输入的消费类别不合法，请重新输入！")
            continue

        amount_input = input("金额：").strip()
        try:
            amount = float(amount_input)
            if amount <= 0:
                raise ValueError("金额必须为正数")
        except ValueError as e:
            print(f"输入的金额不合法：{e}，请重新输入！")
            continue

        category = CATEGORY_MAP[category]  # 转换为中文类别
        records[category] = records.get(category, 0) + amount
    return records

def main():
    # 加载历史记录
    records = load_records(RECORD_FILE)

    # 输入新的消费记录
    new_records = input_records()

    # 合并新旧记录
    for category, amount in new_records.items():
        records[category] = records.get(category, 0) + amount

    # 保存合并后的记录
    save_records(RECORD_FILE, records)

    # 输出统计结果
    print("\n消费统计结果：")
    total_amount = 0
    for category, amount in records.items():
        print(f"{category}：{amount:.2f}元")
        total_amount += amount
    print(f"总消费金额：{total_amount:.2f}元")

    if records:
        max_category = max(records, key=records.get)
        print(f"消费金额最高的类别：{max_category}（{records[max_category]:.2f}元）")

if __name__ == "__main__":
    main()